// pages/personinfo/personInfo.js
import dayjs from '../../miniprogram_npm/dayjs/index'
import { areaList } from '../../miniprogram_npm/@vant/area-data/index';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');
const qiniu = require('../../utils/qiniu-wxapp-sdk-master/qiniuUploader')
var qqmapsdk;
import config from '../../utils/config'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        areaList,
        avator: '',
        gender: '',
        birthday: '',
        location: '',
        nickName: '',
        userId: '',
        show: false,
        showDate: false,
        showLocation: false,
        showName: false,
        currentLocation: '',
        actions: [
            {
                name: '男',
            },
            {
                name: '女',
            },
            {
                name: '不设置',
            },
        ],
        currentDate: new Date().getTime(),
        minDate: new Date('2000-01-01').getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        wx.getStorage({
            "key": 'userInfo',
            success: function (res) {
                that.setData({
                    avator: res.data.avator,
                    gender: res.data.gender,
                    birthday: res.data.birthDay,
                    location: res.data.location,
                    nickName: res.data.nickName,
                    userId: res.data.userId,
                    currentLocation: res.data.currentLocation
                })
            }
        })

        qqmapsdk = new QQMapWX({
            key: 'PCVBZ-OX56A-5F2K6-COJSJ-WHZOJ-42BYD'
        });

    },
    closeOpt() {
        this.setData({
            show: false
        })
    },
    openOpt() {
        this.setData({
            show: true
        })
    },
    selectGender(e) {
        let gender = e.detail.name;
        if (e.detail.name == '不设置') {
            gender = ''
        }
        this.setData({
            gender: gender
        })
        this.closeOpt()
    },

    openBirth() {
        this.setData({
            showDate: true
        })
    },
    selectBirth(e) {
        const birthday = dayjs(e.detail).format('YYYY-MM-DD');
        console.log(birthday);
        this.setData({
            birthday: birthday
        })
        this.closeDate()
    },
    closeDate() {
        this.setData({
            showDate: false
        })
    },
    selectHomeTown() {
        this.setData({
            showLocation: true
        })
    },
    selectLocation() {
        let that = this
        Dialog.confirm({
            title: '获取位置信息',
            message: '是否获取当前位置',
        })
            .then(() => {
                // on confirm
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        console.log('城市名称：', res);
                        const latitude = res.latitude;
                        const longitude = res.longitude;
                        wx.request({
                            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
                            data: {
                                location: `${latitude},${longitude}`,
                                key: 'PCVBZ-OX56A-5F2K6-COJSJ-WHZOJ-42BYD',
                                get_poi: 0
                            },
                            success(res) {
                                const addressComponent = res.data.result.address_component;
                                const province = addressComponent.province;
                                const city = addressComponent.city;
                                that.setData({
                                    currentLocation: city
                                })
                            }
                        })
                    }
                })
            })
            .catch(() => {
                // on cancel
            });

    },
    selectedOver(e) {
        console.log(e.detail.values);
        let str = '', arr = e.detail.values;
        arr.forEach((item) => {
            str += item.name
        })
        this.setData({
            location: str
        })
        this.cancelSelected()
    },
    cancelSelected() {
        this.setData({
            showLocation: false
        })
    },
    saveSetting() {
        wx.request({
            url: `${config.baseUrl}/saveSetting`,
            method: 'POST',
            data: {
                avator: this.data.avator,
                gender: this.data.gender,
                birthday: this.data.birthday,
                location: this.data.location,
                nickName: this.data.nickName,
                currentLocation: this.data.currentLocation,
                userId: this.data.userId
            },
            success: (res) => {

                const data = res.data.data;
                wx.showToast({
                    title: data.msg
                })
                console.log(123);
                wx.setStorageSync('userInfo', Object.assign({ isLogin: true }, data))
                wx.navigateBack()
            }
        })
    },
    onChange(e) {
        this.setData({
            nickName: e.detail
        })
    },
    changeNickname() {
        this.setData({
            showName: true
        })
    },
    changeAvator() {
        wx.chooseMedia({
            mediaType: 'image',
            success: (res) => {
                console.log(res);
                this.getToken(res.tempFiles[0].tempFilePath)
                
            }
        })

    },
    getToken(imgPath) {
        wx.request({
            url: `${config.baseUrl}/getUptoken`,
            method: 'GET',
            success: (res) => {
                console.log('token', res);
                if (res.data.code == 200) {
                    let token = res.data.upToken
                    wx.uploadFile({
                        filePath: imgPath,
                        name: 'file',
                        url: 'https://upload-z2.qiniup.com',
                        formData: {
                            token: token,
                            key: new Date().getTime()
                        },
                        success: (uploadFileRes) => {
                            let strToObj = JSON.parse(uploadFileRes.data);
                            console.log("uploadFileRes", strToObj);
                            let url = 'http://ryih7c40q.hn-bkt.clouddn.com/' + strToObj.key
                            console.log('最终路径',url);
                            this.setData({
                                avator:url
                            })
                        },
                        fail:(err)=>{
                            console.log('err',err);
                        }
                    })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})